<?php
declare (strict_types=1);

namespace app\common\model;

class ProductCate extends Base
{
    protected function child(): object
    {
        return $this->hasMany(ProductCate::class, 'pid')
            ->field('id,pid,title');
    }

    public static function getAll(): array
    {
        try {
            $result = parent::order('sort desc, id asc')->select()->toArray();

        } catch (\Exception $e) {

            return [];
        }

        return self::mergeMenu($result);
    }

    public static function getCate($id = 0): object
    {
        return parent::where(['pid' => $id,'status' => 1])->field("id,icon,title")
            ->order('sort desc, id asc')->select();
    }

    public static function mergeMenu($cate, $pid = 0, $lvl = 0, $left_px = 0): array
    {
        $arr = [];
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $v['lvl'] = $lvl + 1;
                $v['left_px'] = $left_px + 0;//左边距
                $arr[] = $v;
                $arr = array_merge($arr, mergeMenu($cate, $v['id'], $lvl + 1, $left_px + 40));
            }
        }

        return $arr;
    }
}